// (C) 2021 Intel Corporation. All rights reserved.
// Your use of Intel Corporation's design tools, logic functions and other 
// software and tools, and its AMPP partner logic functions, and any output 
// files from any of the foregoing (including device programming or simulation 
// files), and any associated documentation or information are expressly subject 
// to the terms and conditions of the Intel Program License Subscription 
// Agreement, Intel FPGA IP License Agreement, or other applicable 
// license agreement, including, without limitation, that your use is for the 
// sole purpose of programming logic devices manufactured by Intel and sold by 
// Intel or its authorized distributors.  Please refer to the applicable 
// agreement for further details.

module ClkDiv
  #(parameter DIV = 249999)
    (
    input iClk,
    input iRst_n,
     
    output reg div_clk  //output pulse
     );
   
   ///////////////////////////////
   //// local params declaration
   /////////////////////////////////////////////////////////////////////////////////////
         
   localparam  CNT_SIZE = clog2(DIV);


   ///////////////////////////////
   //// local function
   /////////////////////////////////////////////////////////////////////////////////////
   function integer clog2;
      input    integer value;
      begin
         value = value-1;
         for (clog2=0; value>0; clog2=clog2+1)
           value = value>>1;
      end
   endfunction

   ///////////////////////////////
   //// internal signals declaration
   /////////////////////////////////////////////////////////////////////////////////////
         
   reg [CNT_SIZE-1:0] rCnt;      //counter for the divider

   ///////////////////////////////
   //// clock divider always module
   /////////////////////////////////////////////////////////////////////////////////////
   
   always @(posedge iClk, negedge iRst_n)
     begin
        if (!iRst_n)                //asynch active-low reset
          begin
             div_clk <= 1'b0; 
             rCnt <= 0;
          end
        else
          begin
             if (rCnt == DIV)           //when counter reaches the top count specified in DIV param
               begin
                  div_clk <= 1'b1;      //we toggle the divided clock signal
                  rCnt <= 0;            //and reset the counter for the next toggle
               end
             else
               begin
                  div_clk <= 1'b0;       //otherwise, we increment the count and keep the divided clock value steady
                  rCnt <= rCnt + 1'b1;          
               end
          end // else: !if(!iRst_n)
     end // always @ (posedge iClk)
endmodule // ClkDiv

   
   